<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/speculation-rules/prerender/resources/utils.js"></script>
<script src="session-storage-utils.js"></script>
<script>
const params = new URLSearchParams(location.search);
const uid = params.get('uid');

RunSessionStorageTest(async (isPrerendering, url, prerenderChannel, done) => {
  if (!isPrerendering) {
    sessionStorage.setItem('set by initiator page 1', '1');
    startPrerendering(url);
    // Wait for the message from the prerendering page.
    assert_equals(
        await getNextMessage(prerenderChannel),
        'From prerendering page 1')

    // Add an item to the session storage.
    sessionStorage.setItem('set by initiator page 2', '1');

    // Send the message to the prerendering page.
    prerenderChannel.postMessage('From initiator page');

    // Wait for the message from the prerendering page.
    assert_equals(
        await getNextMessage(prerenderChannel),
        'From prerendering page 2')

    // Register beforeunload event handler which adds a new item in the
    // session storage.
    window.addEventListener('beforeunload', () => {
      sessionStorage.setItem('set by initiator page 3', '1');
    });

    // Navigate to the prerenderered page.
    window.location = url;
  } else {
    const prerenderingchangePromise =
        new Promise(resolve => {
            document.addEventListener('prerenderingchange', () => {
              sessionStorage.setItem('set by activated page', 1);
              resolve();
            });
          });

    sessionStorage.setItem('set by prerendering page', '1');

    // Send the message to the initiator page.
    prerenderChannel.postMessage('From prerendering page 1');

    // Wait for the message from the initiator page.
    assert_equals(await getNextMessage(prerenderChannel),
        'From initiator page');

    assert_equals(
        getSessionStorageKeys(),
        'set by initiator page 1, set by prerendering page',
        'The session storage item added by the initiator page after ' +
        'starting prerendering must not be visible in the prerendering ' +
        'page.');

    // Send the message to the initiator page.
    prerenderChannel.postMessage('From prerendering page 2');

    // Wait until activated.
    await prerenderingchangePromise;

    assert_equals(
        getSessionStorageKeys(),
        'set by activated page, set by initiator page 1, ' +
        'set by initiator page 2, set by initiator page 3',
        'The all session storage items added by the initiator page and ' +
        'the item added by the activated page must be visible in the ' +
        'activated page.');
    done();
  }
}, uid);
</script>
